# -*- coding: utf-8 -*-
from google.appengine.ext import webapp,db
from google.appengine.ext.webapp import util,template
from google.appengine.api import memcache
from common import *

import cgi

class MainHandler(RequestHandler):
    def get(self,pid):
        if pid:
            pid=int(pid)
        else:
            pid=1
        if pid==1:
            m=memcache.get('index_entry')
            if m is None:
                m=db.GqlQuery('SELECT * FROM Entry ORDER BY date DESC LIMIT %s' % ENTRY_EACH_PAGE)
                memcache.add('index_entry',m,MEMCACHE_TIME)
            index=memcache.get('index_index')
            if index is None:
                index=MakeIndex(self,pid)
                memcache.add('index_index',index,MEMCACHE_TIME)
        else:
            m=db.GqlQuery('SELECT * FROM Entry ORDER BY date DESC LIMIT %s,%s' % ((pid-1)*ENTRY_EACH_PAGE,ENTRY_EACH_PAGE))
            index=MakeIndex(self,pid)
            
        n=1
        output=[]
        for each in m:
            new=each
            if n%2==0:
                new.side=1
            else:
                new.side=2
            n+=1
            new.image=db.GqlQuery('SELECT * FROM admins WHERE name=:1',each.author)[0].image
            output.append(new)

        del m

        template_values={
            'state':CheckState(self),
            'entries':output,
            'index':index,
            }
        self.Render('index.html',template_values)

    def post(self,pid):
        online=CheckState(self)
        if online:
            new_entry=Entry()
            m=db.GqlQuery('SELECT * FROM Entry ORDER BY uid DESC LIMIT 1')
            if m:
                new_entry.uid=m[0].uid+1
            else:
                new_entry.uid=1
            new_entry.date=GetTime()
            new_entry.content=self.request.get('content').replace(' ','&nbsp;').replace('\n','<br />')
            new_entry.author=online
            new_entry.put()
            current_index=memcache.get('index_index')
            if current_index is None:
                memcache.add('index_index',MakeIndex(self,1),MEMCACHE_TIME)
            else:
                memcache.replace('index_index',MakeIndex(self,1),MEMCACHE_TIME)
            return self.redirect('/')
        else:
            return self.Error(u'=o=')

class Edit(RequestHandler):
    def get(self,uid):
        try:
            entry=db.GqlQuery('SELECT * FROM Entry WHERE uid = :1',int(uid))[0]
        except:
            return self.Error(u'输入的帖子uid不存在')
        else:
            if CheckState(self)==entry.author:
                content=entry.content.replace('<br />','\n')
                template_values={
                    'content':content,
                    }
                return self.Render('edit.html',template_values)
            else:
                return self.Error(u'不让你改')
    def post(self,uid):
        entry=db.GqlQuery('SELECT * FROM Entry WHERE uid=:1',int(uid))
        new_e=entry[0]
        new_e.content=self.request.get('content').replace(' ','&nbsp;').replace('\n','<br />')
        db.put(new_e)
        return self.redirect('/')

class Delete(RequestHandler):
    def get(self,uid):
        try:
            entry=db.GqlQuery('SELECT * FROM Entry WHERE uid=:1',int(uid))[0]
        except:
            return self.Error(u'输入的帖子uid不存在')
        else:
            if CheckState(self)==entry.author:
                db.delete(entry)
                m=memcache.get('index_index')
                if m:
                    m.replace('index_index',MakeIndex(self,1),MEMCACHE_TIME)
                else:
                    memcache.add('index_index',MakeIndex(self,1),MEMCACHE_TIME)
                return self.Error(e=u'搞定',d=u'删除完毕阿鲁')
            else:
                return self.Error(u'想删除别人的帖子是不对的哦')

class InitID(RequestHandler):
    def get(self):
        initID=admins()
        initID.name='udontknow'
        initID.password='iwillknow'
        initID.image='../static/u_head.jpg'
        initID.put()
        return self.Error(e=u'管理员初始化完毕',d=u'管理员你好DAZE！ ゝω･ ')
                          
class Login(RequestHandler):
    def get(self):
        state=False
        m=CheckState(self)
        template_values={
            'state':m,
            }
        if m:
            template_values['name']=m
        else:
            template_values['name']=''
        self.Render('login.html',template_values)
    def post(self):
        m=CheckState(self)
        getid=self.request.get('id')
        getpsd=self.request.get('psd')
        
        if m:
            theID=db.GqlQuery('SELECT * FROM admins WHERE name=:1',m)
            _ID=theID[0]
            if getid is not '':
                _ID.name=getid
            if getpsd is not '':
                _ID.password=getpsd
            db.put(_ID)
            memcache.delete(self.request.remote_addr)
            return self.Error(d=u'需要重新登录',e=u'密码修改完毕')
        else:
            _ID=db.GqlQuery('SELECT * FROM admins')
            if _ID is None:
                return self.Error(u'初始化管理员')
            else:
                for each in _ID:
                    if each.name==getid and each.password==getpsd:
                        memcache.add(self.request.remote_addr,getid,LOGIN_MEMCACHE_TIME)
                        return self.redirect('/')
                else:
                    return self.Error(u'不要捣乱 -_-#')

class Logout(RequestHandler):
    def get(self):
        m=CheckState(self)
        if m:
            memcache.delete(self.request.remote_addr)
            return self.redirect('/')
        else:
            return self.Error(u'咳，我不认识你')

class BadRequest(RequestHandler):
    def get(self):
        return self.Error(d=u'根本就没有这个网页呀',e=u'少女神隐中')
     
def main():
    application = webapp.WSGIApplication([
        ('^/(\d*)$', MainHandler),
        ('^/edit(\d+)$',Edit),
        ('^/delete(\d+)$',Delete),
        ('^/TheC$',Login),
        ('^/Logout$',Logout),
        ('^/woyaochushihuaguanliyuan$',InitID),
        ('/.*',BadRequest),
        ],
                                         debug=True)
    util.run_wsgi_app(application)

# 测试性能
def profile_main():
    import cProfile, pstats
    prof = cProfile.Profile()
    prof = prof.runctx("main()", globals(), locals())
    print "<pre>"
    stats = pstats.Stats(prof)
    stats.sort_stats("time")  # Or cumulative
    stats.print_stats(80)  # 80 = how many to print

    # stats.print_callees()
    # stats.print_callers()
    print "</pre>"

if __name__ == '__main__':
    main()
